const fs = require('fs')

/**
 * 创建component
 */
module.exports = class Component {
    // 构造方法
    constructor(basePath, name) {
        this.basePath = basePath
        this.name = name
        this.error = null
    }

    // 构建文件
    build() {
        let indexTmp = `import Index from './index.vue'
export default Index`

        let viewTmp = `<template>
    <div class="${this.name}-warp">
        {{componentName}}
    </div>
</template>
<script>
export default {
    name: '${this.name}',
    data(){
        return {
            componentName: '${this.name}'
        }
    }
}
</script>
<style lang="less">

</style>`

        // 创建目录及文件
        let dir = `${this.basePath}/components/${this.name}`
        if (fs.existsSync(dir)) {
            this.error = `component ${this.name} exists!`
            return false
        }

        // 创建目录
        fs.mkdirSync(dir)
        // 创建文件
        fs.writeFileSync(`${dir}/index.js`, indexTmp)
        fs.writeFileSync(`${dir}/index.vue`, viewTmp)

        return true
    }

    // 获取错误信息
    getError() {
        let error = this.error
        this.error = null
        return error
    }
}